﻿#region Copyright (c) 2007-2010 Mikko Salmi, Contributors
/*
 *
 * Copyright (c) 2007-2010 Mikko Salmi, Contributors
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
 * 
*/
#endregion // Copyright

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.WebPartPages;

namespace CodePlex.WebParts
{
    [XmlRoot(Namespace = "CodePlex.WebParts")]
    [Guid("70F71E61-A88B-4644-AC89-2C036E34C3CE")]
    public class VideoPlayerWebPart : AdvancedWebPart
    {
        private const string libraryNameDefault = "Video";
        string libraryName = libraryNameDefault;

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable,
        WebDisplayName("Library Name"),
        WebDescription("The name of the library containing video files for video player web part."),
        SPWebCategoryName("Video Player")]
        public string LibraryName
        {
            get
            {
                return libraryName;
            }
            set
            {
                libraryName = value;
            }
        }

        private const int widthDefault = 640;
        int width = widthDefault;

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable,
        WebDisplayName("Player Width"),
        WebDescription("This property represents the width of the player in pixels. The default value is 640 pixels."),
        SPWebCategoryName("Video Player")]
        public int PlayerWidth
        {
            get
            {
                return width;
            }
            set
            {
                width = value;
            }
        }

        private const int heightDefault = 400;
        int height = heightDefault;

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable,
        WebDisplayName("Player Height"),
        WebDescription("This property represents the height of the player in pixels. The default value is 400 pixels."),
        SPWebCategoryName("Video Player")]
        public int PlayerHeight
        {
            get
            {
                return height;
            }
            set
            {
                height = value;
            }
        }

        private const bool startPlayingAtLoadDefault = true;
        bool startPlayingAtLoad = startPlayingAtLoadDefault;

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable,
        WebDisplayName("Start Playing At Page Load"),
        WebDescription(""),
        SPWebCategoryName("Video Player")]
        public bool StartPlayingAtLoad
        {
            get
            {
                return startPlayingAtLoad;
            }
            set
            {
                startPlayingAtLoad = value;
            }
        }

        LiteralControl div;            
       
        public VideoPlayerWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }
        
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            div = new LiteralControl();
            this.Controls.Add(div);

            createJSLinks();

            string playerNumber = getPlayerNumber();

            string source = SPContext.Current.Site.RootWeb.Url + "/_layouts/CodePlex/VideoPlayerWebPart/VideoPlayer.xaml";
            div.Text =
                    "<div id=\"divxamlHost" + playerNumber + "\" style='width:" + width + "px; height: " + height + "px;'>" + "</div>" + Environment.NewLine +
                        "<script type=\"text/javascript\"> " + Environment.NewLine +                       
                        "   var playlistString_" + playerNumber + " = " + createVideoJs() + ";" + Environment.NewLine +                                               
                        "   var source_" + playerNumber + " = '" + source + "';" + Environment.NewLine +
                        "   var player_" + playerNumber + " = new StartPlayer_" + playerNumber + "(); " + Environment.NewLine +
                        "</script>" + Environment.NewLine;            
        }       

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }

        private void createJSLinks()
        {
            SPWeb web = SPContext.Current.Web;

            // Add style sheet to parent page 
            string js1 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/MicrosoftAjax.js";
            createJSLink(js1);

            string js2 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/Silverlight.js";
            createJSLink(js2);

            string js3 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/SilverlightControl.js";
            createJSLink(js3);

            string js4 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/SilverlightMedia.js";
            createJSLink(js4);

            string js5 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/ExpressionPlayer.js";
            createJSLink(js5);

            string js6 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/PlayerStrings.js";
            createJSLink(js6);

            string js7 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/VideoPlayer.js";
            createJSLink(js7);

            string js8 = web.Url + @"/_layouts/CodePlex/VideoPlayerWebPart/StartPlayer.js";
            createJSLink(js8);
        }
        
        private void createJSLink(string js)
        {
            LiteralControl lc = new LiteralControl();
            lc.Text = "<script type=\"text/javascript\" src=\"" + js + "\"></script>" + Environment.NewLine;

            if (this.Page.Header != null)
            {
                this.Page.Header.Controls.Add(lc);
            }
        }

        protected string getPlayerNumber()
        {
            int i = 0;
            foreach (System.Web.UI.WebControls.WebParts.WebPart part in this.WebPartManager.WebParts)
            {
                if (part.GetType() == typeof(VideoPlayerWebPart))
                {
                    if (part.ID == this.ID)
                    {
                        break;
                    }

                    i++;
                }
            }

            return i.ToString();
        }

        private string createVideoJs()
        {            
            SPWeb web = SPContext.Current.Web;

            string videoJs = string.Empty;

            try
            {
                if (web.Lists[libraryName].Items.Count == 0)
                    return string.Empty;

                videoJs = "'this._playlist=['+";

                int i = 1;

                foreach (SPListItem video in web.Lists[libraryName].Items)
                {
                    videoJs +=
                                "'{\"mediaSource\":\"" + video["ows_EncodedAbsUrl"] + "\",'+ " + 
                                "'\"placeholderSource\":\"\",'+ " + 
                                "'\"chapters\":'+" +
                                "'['+" +
		                        "']}'+";

                    if (i < web.Lists[libraryName].ItemCount)
                    {
                        videoJs += "',' +";
                    }

                    i++;
                }
            }
            catch
            {
                // libraryName was not found.
                videoJs = string.Empty;
            }

            videoJs += "'];'";

            //return videoJs;
            return videoJs;		           
        }
    }
}